package com.iot.ic.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by xiuge on 2017/7/18.
 */
public class OkHttpUtil {

    private static Logger logger= LoggerFactory.getLogger(OkHttpUtil.class);


    public static boolean postRequest(Object object,String url) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        String className = object.getClass().getName();
        Class clazz = null;// 根据类名获得其对应的Class对象 写上你想要的类名
        try {
            clazz = Class.forName(className);
            Field[] fields = clazz.getDeclaredFields();// 根据Class对象获得属性 私有的也可以获得
            for (Field f : fields) {
                String name = f.getName();
                Method m = object.getClass().getMethod("get" + firstLetterToUpper(name));// 根据方法名称获取对应属性
                builder.addFormDataPart(name, String.valueOf(m.invoke(object)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response;
        String jsonString;
        try {
            OkHttpClient client = new OkHttpClient();
            response = client.newCall(request).execute();
            jsonString = response.body().string();
            if (jsonString.equals("{\"status\":0,\"message\":\"成功\"}")) {
                return true;
            }else {
                logger.info(jsonString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 首字符大写
     *
     * @param str
     * @return
     */
    public static String firstLetterToUpper(String str) {
        char[] array = str.toCharArray();
        array[0] -= 32;
        return String.valueOf(array);
    }


}
